class Event < ActiveRecord::Base
  acts_as_tree

  has_many :raid_events
  # belongs_to :parent, :class_name => "Event", :foreign_key => "parent_id"
  # has_many :children, :class_name => "Event", :foreign_key => "parent_id", :after_add => :after_add_child

  serialize :serialized_calculation_params, Hash
  serialize :serialized_conversion_params, Hash

  class << self
    def default
      roots = self.roots
      if roots.empty?
        raise "Missing root node in event hierarchy"
      elsif roots.size > 1
        raise "Multiple root nodes in event hierarchy"
      else
        return root
      end
    end

    def roots
      self.find_all_by_parent_id(nil)
    end
  end

  def calculation_params
    begin
      return self.serialized_calculation_params
    rescue ActiveRecord::SerializationTypeMismatch
      return nil
    end
  end

  def calculation_params=(params)
    self.serialized_calculation_params = params
  end

  def conversion_params
    begin
      return self.serialized_conversion_params
    rescue ActiveRecord::SerializationTypeMismatch
      return nil
    end
  end

  def conversion_params=(params)
    self.serialized_conversion_params = params
  end

  def used_calculation_params
    if self.parent == nil
      if self.calculation_params != nil
        return self.calculation_params
      else
        return {}
      end
    else
      if self.calculation_params == nil
        return self.parent.used_calculation_params
      else
        return self.calculation_params
      end
    end
  end

  def used_conversion_params
    if self.parent == nil
      if self.conversion_params !=nil
        return self.conversion_params
      else
        return {}
      end
    else
      if self.conversion_params == nil
        return self.parent.used_conversion_params
      else
        return self.conversion_params
      end
    end
  end

  def calculate_raw_witness(witness)
    time = witness.raid_event.time
    attendances = witness.raid_event.raid.attendances.find(:all, :conditions => {'character_id' => witness.character_id})
    raw_value = 0

    attendances.each do |attendance|
      if ((attendance.jointime <= time) && (attendance.leavetime >= time))
        raw_value = raw_value + 1
      end
    end

    return raw_value
  end

  def convert_raw_witness(witness)
    ratio = used_conversion_params[:ratio]
    if ratio == nil
      raise "Invalid default event / Broken event dependency"
    end
    return witness.raw_value * ratio
  end

end
